package edu.bupt.softsec.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class WriteAliaes {
  // public static void main(String[] args) {
  //
  // }

  public void insertDB(String source, String des, Connection con) {
    int sourceCom = -1;
    int desCom = -1;

    try {

      Statement st = con.createStatement();
      String select1 =
          " SELECT \"Components\".\"id\"" + "FROM \"Classes\", \"Components\", \"Applications\" "
              + "WHERE \"Classes\".\"id\" = \"Components\".\"class_id\" "
              + "AND \"Classes\".\"app_id\" = \"Applications\".\"id\" "
              + "AND \"Classes\".\"class\" = '" + source + "'";
      ResultSet rs1 = st.executeQuery(select1);
      if (rs1.next()) {
        sourceCom = rs1.getInt(1);
      } else {
        System.out.println(source + ":not found");
        return;
      }
      String select2 =
          " SELECT \"Components\".\"id\"" + "FROM \"Classes\", \"Components\", \"Applications\" "
              + "WHERE \"Classes\".\"id\" = \"Components\".\"class_id\" "
              + "AND \"Classes\".\"app_id\" = \"Applications\".\"id\" "
              + "AND \"Classes\".\"class\" = '" + des + "'";
      ResultSet rs2 = st.executeQuery(select2);
      if (rs2.next()) {
        desCom = rs2.getInt(1);
      } else {
        System.out.println(des + ":not found");
        return;
      }

      // System.out.println(sourceCom + "->" + desCom);

      // insert into Aliases
      String aliasSelect =
          "SELECT * FROM \"Aliases\" WHERE component_id=" + sourceCom + " AND target_id=" + desCom;
      ResultSet rsAlias = st.executeQuery(aliasSelect);
      if (!rsAlias.next()) {
        String insertAliases = "INSERT INTO \"Aliases\" (component_id,target_id) VALUES ("
            + sourceCom + "," + desCom + ")";
        st.execute(insertAliases);
        System.out.println("insert success");
      } else {
        System.out.println("exist" + sourceCom + "->" + desCom);
      }

      // close
      rs1.close();
      rs2.close();
      st.close();

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
